<template>
<!-- 服务器性能监测 -->
    <div class="servers-performance-monitor-wrap">
        <div class="model-title">服务器性能监测</div>
        <!-- 筛选条件 -->
        <div class="search-condition">
            <ul class="monitor-type-list">
                <li class="monitor-type-item" :class="{'selected': searchForm.serverType==1}" @click="changMonitorType(1)">CPU</li>
                <li class="monitor-type-item" :class="{'selected': searchForm.serverType==2}" @click="changMonitorType(2)">内存</li>
                <li class="monitor-type-item" :class="{'selected': searchForm.serverType==3}" @click="changMonitorType(3)">磁盘</li>
            </ul>
            <el-select v-model="searchForm.serverId" slot="prepend" placeholder="请选择服务器" @change="changServer()">
                <el-option v-for="item in serverList" :label="item.serverName" :value="item.host.toString()" :key="item.host"></el-option>
            </el-select>
        </div>
        <!-- 展示内容 -->
        <div class="model-content-wrap">
            <div class="server-icon"></div>
            <div class="echart-wrap">
                <!-- CPU统计 -->
                <div class="echart-item-wrap" v-show="searchForm.serverType==1">
                    <p class="echart-item-header">
                        <span class="monitor-type-title">CPU</span>
                        <span class="monitor-type-value">利用率{{ currentServer.CPU }}%</span>
                    </p>
                    <div id="lineEchartCPU" class="server-type-echart"></div>
                </div>
                <!-- 内存统计 -->
                <div class="echart-item-wrap" v-show="searchForm.serverType==2">
                    <p class="echart-item-header">
                        <span class="monitor-type-title">内存</span>
                        <span class="monitor-type-value">利用率{{ currentServer.RAM }}%</span>
                    </p>
                    <div id="lineEchartRAM" class="server-type-echart"></div>
                </div>
                <!-- 磁盘统计 -->
                <div class="echart-item-wrap" v-show="searchForm.serverType==3">
                    <p class="echart-item-header">
                        <span class="monitor-type-title">磁盘</span>
                        <span class="monitor-type-value">利用率{{ currentServer.DISKY }}%</span>
                    </p>
                    <div id="lineEchartDisk" class="server-type-echart"></div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import utils from '@/utils/util'
import { getServerInfoList, getServerInfo } from '@/api/platMonitor'

let Echarts = require("echarts/lib/echarts");
require("echarts/lib/chart/line");
require("echarts/lib/component/tooltip");

export default {
    name: 'ServersPerformanceMonitor',
    data() {
        return {
            serverList: [], // 服务器列表
            searchForm: {
                serverType: 1, // 类别：1-CPU 2-内存 3-磁盘
                serverId: ''
            },
            currentServer: {
                CPU: 0,
                RAM: 0,
                DISKY: 0
            }, // 当前服务器利用率
            currentXAxisData: [], // 当前服务器X轴时间记录
            currentCPUyAxisData: [], // 当前服务器cpu利用率记录
            currentRAMyAxisData: [], // 当前服务器内存利用率记录
            currentDiskyAxisData: [], // 当前服务器磁盘利用率记录
        }
    },
    created() {
        this.getServerList()
        // 设定echart图标的初始宽高,解决初始化不能获取正确宽高问题
        this.$nextTick(() => {
            let initWidth = $('#lineEchartCPU').width()
            let initHeight = $('#lineEchartCPU').height()
            
            document.getElementById('lineEchartRAM').style.width = initWidth + 'px'
            document.getElementById('lineEchartRAM').style.height = initHeight + 'px'
            document.getElementById('lineEchartDisk').style.width = initWidth + 'px'
            document.getElementById('lineEchartDisk').style.height = initHeight + 'px'
        })
    },
    methods: {
        // 获取服务器列表
        getServerList() {
            let that = this
            getServerInfoList().then(res => {
                if(res.status === 200) {
                    this.serverList = res.data
                    this.searchForm.serverId = res.data[0].host
                    this.getServerInfo(res.data[0].host)
                }
            })
        },
        // 获取服务器性能信息
        getServerInfo(id) {
            let that = this
            let serverId = this.searchForm.serverId
            let nowTime = new Date()
            if(id) {
                serverId = id
            }
            getServerInfo({
                hostIP: serverId
            }).then(res => {
                if(res.status === 200) {
                    let item = res.data[0]
                    // 记录当前值
                    this.currentServer = {
                        CPU: Number(item.cpuUsed.replace('%', '')),
                        RAM: utils.accSub(100, Number(item.memoryIdlePercent.replace('%', ''))),
                        DISKY: utils.accSub(100, Number(item.diskIdlePercent.replace('%', '')))
                    }
                    // 添加到数组中
                    that.currentXAxisData.push(utils.ilinkTimeformat.format(nowTime, 'hh:mm:ss'))
                    that.currentCPUyAxisData.push(Number(item.cpuUsed.replace('%', '')))
                    that.currentRAMyAxisData.push(utils.accSub(100, Number(item.memoryIdlePercent.replace('%', ''))))
                    that.currentDiskyAxisData.push(utils.accSub(100, Number(item.diskIdlePercent.replace('%', ''))))
                    
                    this.$nextTick(() => {
                        this.renderLineEchart('lineEchartCPU', that.currentXAxisData, that.currentCPUyAxisData)
                        this.renderLineEchart('lineEchartRAM', that.currentXAxisData, that.currentRAMyAxisData)
                        this.renderLineEchart('lineEchartDisk', that.currentXAxisData, that.currentDiskyAxisData)
                        that.$Ctl.loading(0)
                    })
                    // 开启定时器
                    that.intervalGetServerInfo(60)
                }
            })
        },
        // 切换性能类别
        changMonitorType(type) {
            this.searchForm.serverType = type || 1
        },
        // 切换服务器
        changServer() {
            this.currentServer.CPU = 0
            this.currentServer.RAM = 0
            this.currentServer.DISKY = 0
            // 上一次记录的数据清除
            this.currentxAxisData = []
            this.currentCPUyAxisData = []
            this.currentRAMyAxisData = []
            this.currentDiskyAxisData = []
            this.getServerInfo()
        },
        // 绘制折线图
        renderLineEchart(id, xAxisData, yAxisData) {
            let that = this
            let domId = id
            let option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: '{b}<br />{a}:{c}%'
                },
                grid: {
                    show: true,
                    top: 10,
                    bottom: 20,
                    borderColor: 'rgba(97,186,242,.1)'
                },
                xAxis: [{
                    type: 'category',
                    data: xAxisData,
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(97,186,242,.1)'
                        }
                    },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: "rgba(255,255,255,.1)"
                        }
                    },
                    axisTick: {
                        show: false,
                        alignWithLabel: true
                    },
                }],
                yAxis: [{
                    type: 'value',
                    splitNumber: 5,
                    min: 0,
                    max: 100,
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(97,186,242,.1)'
                        }
                    },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: "rgba(97,186,242,.1)"
                        },
                    },
                    axisTick: {
                        show: false  
                    },
                    splitArea: {
                        show: false
                    }
                }],
                series: [{
                    name: '利用率',
                    type: 'line',
                    data: yAxisData,
                    lineStyle: {
                        normal: {
                            width: 2,
                            color: '#61BAF2'
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: '#61BAF2',
                            borderWidth: 0,
                            borderColor: "#61BAF2"
                        }
                    },
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0, color: '#5371DC' // 0% 处的颜色
                            }, {
                                offset: 1, color: '#58C6F3' // 100% 处的颜色
                            }],
                        }
                    },
                    smooth: true
                }]
            }

            if(document.getElementById(domId)) {
                Echarts.init(
                    document.getElementById(domId)
                ).setOption(option);
            }
        },
        /* 定时任务，每隔一段时间请求服务器信息
         * time：周期 （单位：s）默认10分钟
         */
        intervalGetServerInfo(time) {
            let that = this
            let timeCycle = (time || 600)*1000
            // 清除定时器
            if(window.setverMonitorInterValObj) {
                clearInterval(window.setverMonitorInterValObj)
                window.setverMonitorInterValObj = null
            }
            window.setverMonitorInterValObj = setInterval(() => {
                that.getServerInfo()
            }, timeCycle)
        }
    }
}
</script>
<style lang="scss">
.servers-performance-monitor-wrap {
    position: relative;
    .search-condition {
        position: absolute;
        top: 20px;
        right: 50px;
        display: flex;
        align-items: center;
        .monitor-type-list {
            display: flex;
            margin-right: 30px;
            height: 40px;
            border: 1px solid rgba(104,169,255,.4);
            border-left: none;
            color: #A3BEDD;
            .monitor-type-item {
                border-left: 1px solid rgba(104,169,255,.4);
                padding: 6px 15px;
                font-size: 18px;
                &.selected {
                    background:rgba(19,76,153,.8);
                }
            }
        }
    }
    .model-content-wrap {
        display: flex;
        margin-top: 20px;
        width: 100%;
        height: calc(100% - 50px);
        .server-icon {
            width: 350px;
            height: 100%;
            background: url(../../../../../assets/images/detailPage/server-monitor.gif) center center no-repeat;
        }
        .echart-wrap {
            width: calc(100% - 350px);
            height: 100%;
            .echart-item-wrap {
                width: 100%;
                height: 100%;
                .echart-item-header {
                    display: flex;
                    height: 30px;
                    line-height: 30px;
                    justify-content: space-between;
                    .monitor-type-title {
                        color: #57A8FB;
                        font-size: 26px;
                        font-weight: bold;
                    }
                    .monitor-type-value {
                        font-size: 18px;
                        color:rgba(255,255,255,.2);
                    }
                }
                .server-type-echart {
                    margin-top: 20px;
                    width: 100%;
                    height: calc(100% - 50px);
                }
            }
        }
    }
}
</style>
